package com.uduew.sjd.ui.mine

import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.activity.OnBackPressedCallback
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.api.RepaymentScheduleApi
import com.uduew.sjd.bean.CustomerBean
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.RepaymentScheduleRequester
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.uduew.sjd.view.xpop.CustomerXpop
import com.uduew.sjd.view.xpop.RepaymentDetailsXpop
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.uduew.sjd.api.AllLoanOrdersApi
import com.uduew.sjd.config.Const
import com.uduew.sjd.request.RepaymentRequester
import com.uduew.sjd.utils.SpannableUtils

class LoanDetailFragment : BaseFragment() {

    lateinit var mState: LoanDetailStates
    private lateinit var mMessenger: PageMessenger
    private lateinit var mRepaymentScheduleRequester: RepaymentScheduleRequester
    private var orderDetail: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean? = null
    private lateinit var mRepaymentRequester: RepaymentRequester
    override fun initViewModel() {
        mState = getFragmentScopeViewModel(LoanDetailStates::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
        mRepaymentScheduleRequester =
            getFragmentScopeViewModel(RepaymentScheduleRequester::class.java)//还款计划
        mRepaymentRequester = getActivityScopeViewModel(RepaymentRequester::class.java) //获取借款账单
    }

    private fun setData() {
        orderDetail?.let {
            mState.nuciform.set(it.nuciform)
            mState.nuciformStr.set(it.nuciformStr)
            mState.phylogenic.set(it.phylogenic)
            mState.beastly.set(it.beastly)
            mState.tubulure.set(it.tubulure)
            val date = Utils.timestampToDate(it.irrelevant.toLong())
            mState.irrelevant.set(date)
        }
        getDetail()
    }

    private fun getDetail() {
        if (mState.phylogenic.get() == "firemen" || mState.phylogenic.get() == "breeks") {
            mState.beastly.get().let {
                if (it != null) {
                    WaitDialog.show(getString(R.string.loading))
                    mRepaymentScheduleRequester.request(this, it)
                }
            }
        }
    }

    fun getOrderDetail(): AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean? {
        val orderDetail: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean? =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                arguments?.getParcelable(
                    "orderDetail",
                    AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean::class.java
                )
            } else {
                @Suppress("DEPRECATION")
                arguments?.getParcelable<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>(
                    "orderDetail"
                )
            }
        return orderDetail

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        orderDetail = arguments?.getParcelable("orderDetail")
        requireActivity().onBackPressedDispatcher.addCallback(
            viewLifecycleOwner,
            backPressCallback
        )
        if (orderDetail != null) {
            setData()
        } else {
            val debrief = ArrayList<String>()
            debrief.add("firemen") //待还
            debrief.add("underwent") //审批中
            debrief.add("breeks") //逾期
            mRepaymentRequester.request(
                viewLifecycleOwner,
                "", debrief,
                1, 10
            )
        }
        mRepaymentRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<AllLoanOrdersApi.ResAllLoanOrdersBean> ->
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                it.mamaguy.thorough.let {
                    if (it.isNotEmpty()) {
                        orderDetail = it[0]
                        setData()
                    }
                }

            }
        }

        mRepaymentScheduleRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<HttpBean<RepaymentScheduleApi.ResRepaymentScheduleBean>> ->
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.data.let {
                if (it != null) {
                    mState.tubulure.set(it.tubulure)
                    mState.telegraphoscope.set(it.telegraphoscope)
                    mState.strabismal.set(it.strabismal)
                    if (mState.isRepayment == true) {
                        mState.isRepayment = false
                        showDetail(
                            it.telegraphoscope.toString(),
                            it.herzegovina.toString(),
                            it.strabismal.toString(),
                            "",
                            "",
                            it.tubulure.toString(),
                            ""
                        )
                    }

                }
            }
        }
    }


    fun showDetail(
        amountReceived: String,
        interestInterest: String,
        serviceFee: String,
        taxesFees: String,
        channelMount: String,
        totalAmount: String,
        creditService: String
    ) {
        var pop = RepaymentDetailsXpop(
            requireActivity(),
            amountReceived,
            interestInterest,
            serviceFee,
            taxesFees,
            channelMount,
            totalAmount,
            creditService
        )
        pop.setOnAgreeClickListener {
        }
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(pop)
            .show()
    }


    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.fragment_loan_detail, BR.vm, mState).addBindingParam(
            BR.click,
            Click()
        )
    }

    override fun onResume() {
        super.onResume()
        backPressCallback.isEnabled = true
    }

    fun backAndFinish() {
        if (!Utils.checkDebounce()) return
        val shouldViewOrder = getOrderDetail() == null
        if (shouldViewOrder == true) {
            requireActivity().finish()
        } else {
            nav().popBackStack()
        }
    }


    //监听返回键
    private val backPressCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            backAndFinish() // 复用已封装的返回逻辑
        }
    }

    inner class Click {
        fun extension() {//展期还款
            if (!Utils.checkDebounce()) return
            val bundle = Bundle().apply {
                putParcelable("orderDetail", orderDetail)
            }
            backPressCallback.isEnabled = false
            val shouldViewOrder = getOrderDetail() == null
            if (shouldViewOrder == true) {
                nav().navigate(
                    R.id.action_navigation_main_to_extension_detail_fragment,
                    bundle
                )
            } else {
                nav().navigate(
                    R.id.action_navigation_loan_detail_to_extension_detail_fragment,
                    bundle
                )

            }
        }

        fun service() {
            if (mState.phylogenic.get() == "culminate" || mState.phylogenic.get() == "pathetical") { //联系客服
                var customerBean = CustomerBean(
                    "+86 13240445359",
                    "13240445359@163.com",
                    "13240445359",
                    "13240445359@163.com"
                );
                val mCustomerXpop = CustomerXpop(requireContext(), customerBean)
                XPopup.Builder(requireContext())
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                    .asCustom(mCustomerXpop)
                    .show()
            } else if (mState.phylogenic.get() == "missive") { //再借一笔
                nav().popBackStack()
                mMessenger.input(Messages(Messages.EVENT_SELECT_BACK))
            } else { //立即还款
                val bundle = Bundle().apply {
                    putParcelable("orderDetail", orderDetail)
                }
                backPressCallback.isEnabled = false
                val shouldViewOrder = getOrderDetail() == null
                if (shouldViewOrder == true) {
                    nav().navigate(
                        R.id.action_navigation_main_to_repayment_detail_fragment,
                        bundle
                    )
                } else {
                    nav().navigate(
                        R.id.action_navigation_loan_detail_to_repayment_detail_fragment,
                        bundle
                    )
                }
            }
        }


        fun back() {
            backAndFinish()
        }
    }

    class LoanDetailStates : StateHolder() {
        val nuciform: State<Double> = State(0.0)
        val nuciformStr: State<String> = State("")
        val phylogenic: State<String> = State("")
        val beastly: State<String> = State("")
        val tubulure: State<Double> = State(0.0) //应还金额
        val telegraphoscope: State<Double> = State(0.0)//到账金额
        val strabismal: State<Double> = State(0.0) //利息 serviceAmount
        var isRepayment: Boolean = false
        val irrelevant: State<String> = State("") //申请时间
    }

}